﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using CharacterAnimationEditor;
using WinFormsGraphicsDevice;
using System.IO;
using CakeAnimation;
using Microsoft.Win32;
using System.Xml;

namespace CakeWPF
{


    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {

        Project m_Project;
        XnaControl m_XnaControl;
        HelpDisplay m_HelpDisplay;
        string startWorkingDir = Environment.CurrentDirectory;


        public Window1()
        {
            InitializeComponent();

            m_XnaControl = new XnaControl();
            m_XnaControl.Dock = System.Windows.Forms.DockStyle.Fill;
            RenderPanel.Controls.Add(m_XnaControl);
            m_XnaControl.Select();
            m_XnaControl.Focus();
            // RenderPanel.MouseWheel+=new System.Windows.Forms.MouseEventHandler(RenderPanel_MouseWheel);

            m_HelpDisplay = new HelpDisplay();
            //m_XnaControl.m_Context.HelpDisplay = m_HelpDisplay;
            m_HelpDisplay.TextUpdated += new EventHandler(m_HelpDisplay_TextUpdated);

            m_XnaControl.MouseClick += new System.Windows.Forms.MouseEventHandler(m_XnaControl_MouseClick);
            m_XnaControl.MouseUp += new System.Windows.Forms.MouseEventHandler(m_XnaControl_MouseUp);
        }

        void m_HelpDisplay_TextUpdated(object sender, EventArgs e)
        {
            statusText.Text = m_HelpDisplay.m_Caption + " :: " + m_HelpDisplay.m_Text;
        }

        void m_XnaControl_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            ContextMenu = new ContextMenu();
            ContextMenu.Items.Add("hej");
            //ContextMenu.
        }
        void m_XnaControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            m_XnaControl.Select();
            m_XnaControl.Focus();
        }

        private void MenuItemExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void OpenProject_Click(object sender, RoutedEventArgs e)
        {
            BrowseForProject();

            if (AnimDirValue.Text != "")
            {
                m_Project = new Project();
                m_Project.Load(m_XnaControl.m_Context, AnimDirValue.Text);
                RebuildAnimationList();

                m_XnaControl.Select();
                m_XnaControl.Focus();
            }
        }

        private void BrowseForProject()
        {
            System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
            dlg.FileName = System.IO.Path.GetFullPath(System.IO.Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\..\\CharacterAnimationEditor/Content/samples.cakeproj"));
            System.Windows.Forms.DialogResult res = dlg.ShowDialog();
            Environment.CurrentDirectory = startWorkingDir;

            string projectFile = dlg.FileName;
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            Properties.Settings.Default.ProjectPath = projectFile;
            Properties.Settings.Default.Save();

            AnimDirValue.Text = dlg.FileName;
        }

        private void BrowseForFolder()
        {
            System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
            dlg.SelectedPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\..\\CharacterAnimationEditor/Content"));

            System.Windows.Forms.DialogResult res = dlg.ShowDialog();
            Environment.CurrentDirectory = startWorkingDir;
            if (res != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            AnimDirValue.Text = System.IO.Path.GetFullPath(dlg.SelectedPath); ;

            RebuildAnimationList();

            m_XnaControl.Select();
            m_XnaControl.Focus();
        }

        private void RebuildAnimationList()
        {
            AnimationList.Items.Clear();

            foreach (Animation anim in m_Project.Animations)
            {
                ListViewItem item = new ListViewItem();
                item.Content = anim;
                AnimationList.Items.Add(item);
            }

        }


        private void AnimationList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count == 0)
            {
                return;
            }


            Animation anim = ((ListViewItem)e.AddedItems[0]).Content as Animation;
            m_XnaControl.m_Context.Animation = anim;
            m_XnaControl.m_Context.SetCurrentKeyFrame(anim.m_Keyframes[0]);

            LoopCheckbox.IsChecked = anim.Loopable;

            RigView.Items.Clear();
            CreateRigTree(anim.m_Keyframes[0].Pose.RootBone, null);

            Environment.CurrentDirectory = startWorkingDir;

            AnimDirValue.IsEnabled = false;
            AnimDirValue.MouseDown += new MouseButtonEventHandler(delegate(object o1, System.Windows.Input.MouseButtonEventArgs o2) { AnimDirValue.IsEnabled = false; });
            //AnimDirValue.MouseLeave += new MouseButtonEventHandler(delegate(object o1, System.Windows.Input.MouseButtonEventArgs o2) { AnimDirValue.IsEnabled = true; });
        }

        public void CreateRigTree(Bone bone, TreeViewItem parentTreeItem)
        {
            TreeViewItem newParent = new TreeViewItem();
            newParent.Header = bone.Name;
            newParent.IsExpanded = true;
            if (parentTreeItem == null)
            {
                RigView.Items.Add(newParent);
            }
            else
            {
                parentTreeItem.Items.Add(newParent);
            }

            foreach (Bone childBone in bone.Children)
            {
                CreateRigTree(childBone, newParent);
            }
        }

        private void SaveAnimationButton_Click(object sender, RoutedEventArgs e)
        {
            ListViewItem item = (ListViewItem)AnimationList.SelectedItem;
            string filename = item.Content.ToString();
            string folder = System.IO.Path.GetDirectoryName((string)AnimDirValue.Text);
            string path = System.IO.Path.Combine(folder, filename + ".anim");

            AnimationSerializer s = new AnimationSerializer();
            s.SaveAnimation(m_XnaControl.m_Context.Animation, path);
        }

        private void SaveAsAnimationButton_Click(object sender, RoutedEventArgs e)
        {
            ListViewItem item = (ListViewItem)AnimationList.SelectedItem;
            string filename = item == null ? "Unnamed" : item.Content.ToString();
            string path = System.IO.Path.Combine((string)AnimDirValue.Text, filename + ".anim");

            FileDialog dlg = new SaveFileDialog();
            dlg.DefaultExt = "anim";
            dlg.FileName = path;
            dlg.AddExtension = true;
            dlg.ShowDialog();


            AnimationSerializer s = new AnimationSerializer();
            s.SaveAnimation(m_XnaControl.m_Context.Animation, dlg.FileName);

            Environment.CurrentDirectory = startWorkingDir;

            m_Project = new Project();
            m_Project.Load(m_XnaControl.m_Context, AnimDirValue.Text);

            RebuildAnimationList();

            Properties.Settings.Default.ProjectPath = AnimDirValue.Text;
            Properties.Settings.Default.Save();

            m_XnaControl.Select();
            m_XnaControl.Focus();       
        }

        private void FilterCheckbox_Checked(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)RigView.SelectedItem;
            if (item == null)
            {
                return;
            }

            bool check = (bool)((CheckBox)sender).IsChecked;
            foreach (KeyFrame kf in m_XnaControl.m_Context.Animation.m_Keyframes)
            {
                Bone b = kf.Pose.GetBone(item.Header.ToString());
                b.Filtered = check;
            }
        }


        private void LoopCheckbox_Checked(object sender, RoutedEventArgs e)
        {
            Animation anim = ((ListViewItem)AnimationList.SelectedItem).Content as Animation;
            anim.Loopable = (bool)((CheckBox)sender).IsChecked;
        }

        private void RigView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            TreeViewItem item = (TreeViewItem)RigView.SelectedItem;
            if (item == null)
            {
                return;
            }


            Bone b = m_XnaControl.m_Context.Animation.GetLastKeyframe().Pose.GetBone(item.Header.ToString());
            FilterCheckbox.IsChecked = b.Filtered;
        }


        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            m_XnaControl.m_Context.HelpDisplay = m_HelpDisplay;
            if (Properties.Settings.Default.ProjectPath == "")
            {
                BrowseForProject();
            }
            else
            {
                AnimDirValue.Text = Properties.Settings.Default.ProjectPath;
            }

            if (AnimDirValue.Text != "")
            {
                try
                {
                    m_Project = new Project();
                    m_Project.Load(m_XnaControl.m_Context, AnimDirValue.Text);

                    RebuildAnimationList();

                    Properties.Settings.Default.ProjectPath = AnimDirValue.Text;
                    Properties.Settings.Default.Save();

                    m_XnaControl.Select();
                    m_XnaControl.Focus();       
                }
                catch (System.Exception ex)
                {         	
                }

            }
        }

        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (e.AddedItems.Count > 0)
            {
                EditorTabControl.Background = ((TabItem)e.AddedItems[0]).Background;
            }
        }

        private void PreviewAnimAddButton_Click(object sender, RoutedEventArgs e)
        {
            ListViewItem item = (ListViewItem)AnimationList.SelectedItem;
            if (item == null)
            {
                return;
            }

            Animation anim = item.Content as Animation;
            AnimationPreviewList.Items.Add(anim);

            List<Animation> anims = m_XnaControl.m_Editor.m_PlayGui.Sequence.AnimationsToPlay;
            anims.Clear();

            foreach (Animation animitem in AnimationPreviewList.Items)
            {

                anims.Add(animitem);
            }
        }

        private void PreviewAnimClearButton_Click(object sender, RoutedEventArgs e)
        {
            AnimationPreviewList.Items.Clear();

            m_XnaControl.m_Editor.m_PlayGui.Sequence.AnimationsToPlay.Clear();
            m_XnaControl.m_Editor.m_PlayGui.Sequence.Reset();
        }

        private void AnimDirValue_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox me = (TextBox)sender;
            if (!System.IO.Directory.Exists(me.Text))
                return;
            RebuildAnimationList();
        }

        private void SaveProject_Click(object sender, RoutedEventArgs e)
        {
            m_Project.Save(AnimDirValue.Text);
        }
    }
}
